﻿<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>摄像头拍照</title>
</head>
<body>
    <img id="imgShow" />
    <div>
        <select id="selectCamera"></select>
        <button id="cameraSwich">打开摄像头</button>
		<input type="range" id="range1" min="100" max="1000" step="50" onchange="b.value=this.value"/>
		<output id="b" for="range1" ></output>
        <button id="capture">拍照</button>
        <!--<button id="close-camera">关闭摄像头</button>-->
		<a id="saveimg" download='snap.jpg'>保存到本地</a>
        <button id="uploadimg">上传</button>
        <button id="showpicbtn">显示</button>
        <input id="picID" type="hidden" value="" />
    </div>
	<div id="videoInformation">
	</div>
    <video id="video" controls="controls" style="border:1px solid #000000;"></video>
    <canvas id="canvas" style="border:1px solid #000000;" ></canvas>
    <script>
        //访问用户媒体设备的兼容方法
        function getUserMedia(constraints, success, error) {
            if (navigator.mediaDevices.getUserMedia) {
                //最新的标准API
                navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
            } else if (navigator.webkitGetUserMedia) {
                //webkit核心浏览器
                navigator.webkitGetUserMedia(constraints, success, error)
            } else if (navigator.mozGetUserMedia) {
                //firfox浏览器
                navigator.mozGetUserMedia(constraints, success, error);
            } else if (navigator.getUserMedia) {
                //旧版API
                navigator.getUserMedia(constraints, success, error);
            }
        }

        let video = document.getElementById('video');
        let canvas = document.getElementById('canvas');
        let context = canvas.getContext('2d');
		let cameraSwich = document.getElementById('cameraSwich');
        var mediaStreamTrack;
		var isOpenCamera = false;
		
        function success(stream) {
            //兼容webkit核心浏览器
            let CompatibleURL = window.URL || window.webkitURL;
            //将视频流设置为video元素的源
            console.log(stream);
            mediaStreamTrack = stream;
            //video.src = CompatibleURL.createObjectURL(stream);
            video.srcObject = stream;
			/*video.onloadedmetadata = function() {
			  console.log('width is', this.videoWidth);
			  console.log('height is', this.videoHeight);
			}*/
            video.play();
			isOpenCamera = true;
			cameraSwich.innerText = "关闭摄像头";
        }

        function error(error) {
            console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
        }

        function closeCamera() {
            mediaStreamTrack.getTracks()[0].stop();
            /*$("#take-picture").attr('disabled',true)
            $("#take-picture").removeClass('btn-primary')
            $("#take-picture").removeClass('btn-danger')
            $("#close-camera").removeClass('btn-primary')
            $("#close-camera").attr('disabled',true)*/
			isOpenCamera = false;
			cameraSwich.innerText = "打开摄像头";
        }

        function showPic() {
            var guid = document.getElementById("picID");

            var xmlHttp = new XMLHttpRequest();
            xmlHttp.open("GET", "../ShowImage.ashx?ID=" + guid.value);
            //xmlHttp.setRequestHeader("Authorization", 'Bearer ' + localStorage.token);//设置请求header,按需设定，非必须
            //xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");//设置请求header,按需设定，非必须
            xmlHttp.responseType = "blob";

            xmlHttp.send();
            xmlHttp.onload = (data) => {
                //todo  your code...

                var blob = xmlHttp.response;
                //var img = document.createElement("img");
                var img = document.getElementById("imgShow");
                img.onload = function (e) {
                    window.URL.revokeObjectURL(img.src);
                };
                img.src = window.URL.createObjectURL(blob);
                //var picsrc = document.getElementById("imgShow");
                //picsrc.setAttribute("src", xmlHttp.responseText);
            };
        }

        function handleSave() {
            //导出base64格式的图片数据
            //var mycanvas = document.getElementById("mycanvas");
            var base64Data = canvas.toDataURL("image/jpeg", 1.0);
            //var base64Data = mycanvas.toDataURL("image/jpeg", 1.0);
            //封装blob对象
            var blob = dataURItoBlob(base64Data);
            //组装formdata
            var fd = new FormData();
            fd.append("fileData", blob);//fileData为自定义
            var fileName = generFileName() + ".jpg";
            //fd.append("fileName", "123jpg");//fileName为自定义，名字随机生成或者写死，看需求
            fd.append("fileName", fileName);
            //ajax上传，ajax的形式随意，JQ的写法也没有问题
            //需要注意的是服务端需要设定，允许跨域请求。数据接收的方式和<input type="file"/> 上传的文件没有区别
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.open("POST", "./useCameraHandler.ashx");
            //xmlHttp.setRequestHeader("Authorization", 'Bearer ' + localStorage.token);//设置请求header,按需设定，非必须
            //xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");//设置请求header,按需设定，非必须
            xmlHttp.send(fd);
            //ajax回调
            //xmlHttp.onreadystatechange = (data) => {
            xmlHttp.onload = (data) => {
                //todo  your code...
                var guid = document.getElementById("picID");
                console.log(data);
                console.log(xmlHttp.responseText);
                //var strdata = JSON.parse(data);
                var strdata = xmlHttp.responseText;
                var l = strdata.indexOf("ID");
                guid.value = strdata.substring(l + 2);
            };
        };

        function dataURItoBlob(base64Data) {
            var byteString;
            if (base64Data.split(',')[0].indexOf('base64') >= 0)
                byteString = atob(base64Data.split(',')[1]);
            else
                byteString = unescape(base64Data.split(',')[1]);
            var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
            var ia = new Uint8Array(byteString.length);
            for (var i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i);
            }
            return new Blob([ia], { type: mimeString });
        };

        function generFileName() {
            var nowDate = new Date();
            var year = nowDate.getFullYear();
            var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1)
                : nowDate.getMonth() + 1;
            var day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
            var dateStr = year + month + day + parseInt(1000 * Math.random());
            return dateStr;
        }

        function openCamera() {
            var sourceId = document.getElementById("selectCamera");
            var index = sourceId.selectedIndex; // 选中索引
            var text = sourceId.options[index].text; // 选中文本
            var value = sourceId.options[index].value; // 选中值
            if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
                //调用用户媒体设备, 访问摄像头
                getUserMedia({
                    video: {
                        //width: 1920,
                        //height: 1080,
                        optional: [{
                            //'sourceId': exArray[1] //0为前置摄像头，1为后置
                            sourceId: value //0为前置摄像头，1为后置
                        }]
                    }
                }, success, error);
            } else {
                alert('不支持访问用户媒体');
            }
        }
        
        var exArray = [];
		var width,height;
		
        if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
            console.log("enumerateDevices() not supported.");
            //return;
        }
        else {
            // List cameras and microphones.
            navigator.mediaDevices.enumerateDevices()
                .then(function (devices) {
                    var select_input = document.getElementById("selectCamera");
					let count=1;
                    devices.forEach(function (device) {
                        console.log(device.kind + ": " + device.label +
                            " id = " + device.deviceId);
                        if (device.kind === 'videoinput') {
                            select_input.options.add(new Option(device.label||`Camera ${count++}`, device.deviceId));
                        }
                    });
                })
                .catch(function (err) {
                    console.log(err.name + ": " + err.message);
                });
        }
        /*MediaStreamTrack.getSources(function (sourceInfos) {
            var select_input = document.getElementById("selectCamera");
            for (var i = 0; i != sourceInfos.length; ++i) {
                var sourceInfo = sourceInfos[i];
                //这里会遍历audio,video，所以要加以区分
                console.log(sourceInfo);
                if (sourceInfo.kind === 'video') {
                    //exArray.push(sourceInfo.id);
                    select_input.options.add(new Option(sourceInfo.id, sourceInfo.id));
                }
            }
            //if (exArray.length > 0)
            //    generSelect();
        });
        */
        //function generSelect() { 
        //}
		
		//先求最大公约数，再约分
		function calcFraction(num1,num2){
			var arr = [];
			let result = (a,b)=>{
			if(b == 0)
				return a;
			let r = a % b;
				return result(b,r);
			}
			num1 >= num2 ? (a = num1, b = num2):(a = num2, b = num1)
			let g = result(a, b);
			arr[0] = num1 / g;
			arr[1] = num2 / g;
			return arr;
		}
		
        document.getElementById('capture').addEventListener('click', function () {
			var zoomSize = document.getElementById('b').value;
			
			var msg;
			if(zoomSize == ''){
				msg=`您未设置缩放比例，图片大小将使用${width}*${height}`;
			}else{
				var arr = calcFraction(width,height);
				width = arr[0]*zoomSize;
				height = arr[1]*zoomSize;
				msg=`您设置缩放比例为:${zoomSize}，图片大小将使用${arr[0]*zoomSize}*${arr[1]*zoomSize}`;
			}
			canvas.width = width;
			canvas.height = height;
			var text=`<br/>图片宽度为：${width} 高度为：${height}`;
			document.getElementById("videoInformation").innerHtml = text;
			if(confirm(msg)){
				context.drawImage(video, 0, 0, width, height);
				var saveimg = document.getElementById('saveimg');
				var url = canvas.toDataURL('image/jpeg',1.0);
				saveimg.href = url;
				saveimg.download="Snap_" + generFileName() +".jpg";
			}else{
				alert('好吧，您再考虑考虑(>_<)')
			}
        })


        /*document.getElementById('close-camera').addEventListener('click', function () {
            closeCamera();
        })*/

        document.getElementById('uploadimg').addEventListener('click', function () {
            handleSave();
            })

        document.getElementById('showpicbtn').addEventListener('click', function () {
            showPic();
        })

        document.getElementById('cameraSwich').addEventListener('click', function () {
            if(!isOpenCamera)
				openCamera();
			else
				closeCamera();
        })

        document.getElementById('video').addEventListener('loadedmetadata', (e) => {
            //alert(e.target.readyState)
            if (e.target.readyState > 0) {
                //alert('w：' + e.target.videoWidth + 'h：' + e.target.videoHeight);
				width = e.target.videoWidth;
				height = e.target.videoHeight;
				//canvas.width = width;
				//canvas.height = height;
				var text=`视频宽度为：${width} 高度为：${height}`;
				document.getElementById("videoInformation").innerText = text;
            }
        })
    </script>
</body>
</html>